package qf.controller;

import org.apache.commons.beanutils.BeanUtils;
import qf.dao.UserDao;
import qf.dao.daoImpl.UserDaoImpl;
import qf.pojo.User;
import qf.service.UserService;
import qf.service.serviceImpl.UserServiceImpl;
import qf.utils.*;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

/**
 * @author 86198
 * @version V1.0
 * @Project Java_qf
 * @Package qf.controller
 * @Description:
 * @Date 2022/5/21 21:42
 */
@WebServlet("/user")
public class UserController extends BaseServlet{
    private UserDao userDao = new UserDaoImpl();
    private UserService userService = new UserServiceImpl(userDao);
    /**
     * 会员登录功能
     */
    public String login(HttpServletRequest request, HttpServletResponse response){
        //获取前端传来的 密码，用户名和验证码的值
        String auto = request.getParameter("auto");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String code = request.getParameter("code");
        //获取生成验证码的值
        String code1 = (String)request.getSession().getAttribute("codes");
        User user = userService.findUsers(username, password);
        //判断是否有此用户；没有返回登陆页面，并提示账号或密码错误
        if (user == null) {
            request.setAttribute("msg","账号或密码错误");
            return Constants.FORWARD + request.getContextPath() + "login.jsp";
        }
        //判断是否激活；没有返回登陆页面，并提示账号或密码错误
        if (!user.getStatus().equals(Constants.USER_ACTIVE)) {
            request.setAttribute("msg","账号未激活");
            return Constants.FORWARD + request.getContextPath() + "login.jsp";
        }
        //判断验证码是否正确，如果不正确返回登陆页面，并提示验证码错误
        if (code == null || !code1.equalsIgnoreCase(code)) {
            request.setAttribute("userName",username);
            request.setAttribute("password",password);
            request.setAttribute("msg","验证码错误");
            return Constants.FORWARD + request.getContextPath() + "login.jsp";
        }
        //将获取的user对象放到域中
        request.getSession().setAttribute("loginUser",user);
        //添加自动登录功能
        if (auto == null) {
            //没有勾选自动登录功能
            Cookie autoUser = new Cookie(Constants.AUTO_NAME, "");
            //将cookie的生命周期修改
            autoUser.setMaxAge(0);
            //所有都可以访问cooki
            autoUser.setPath("/");
            //添加cooki对象
            response.addCookie(autoUser);
        }else{
            String content = username + Constants.FLAG + password;
            content=  Base64Utils.encode(content);
            Cookie autoUser = new Cookie(Constants.AUTO_NAME, content);
            autoUser.setMaxAge(14*24*60*60);
            autoUser.setPath("/");
            response.addCookie(autoUser);
        }

        //调转到其他页面内
        return "redirect:" + request.getContextPath() + "/goods?method=index";
    }
    /**
     * 判断用户名是否重复，不重复可注册，重复不可注册
     */
    public String check(HttpServletRequest request,HttpServletResponse response){
        String username = request.getParameter("username");
        if (username == null) {
            return Constants.HAS_USER;
        }
        boolean userName = userService.findUserName(username);
        if (userName) {
            return Constants.HAS_USER;
        }else{
            return Constants.NOT_HAS_USER;
        }
    }

    public String register(HttpServletRequest request, HttpServletResponse response){
        //获取页面的所有参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        //使用BeanUtils给user赋值
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        //给激活赋值
        user.setStatus(Constants.HAS_USER);
        //给角色赋值
        user.setRole(Constants.ROLE_CUSTOMER);
        //给激活码赋值
        user.setCode(RandomUtils.createActive());

        //给密码处理为加密的属性
        user.setPassword(MD5Utils.md5(user.getPassword()));
        int TorF = userService.registerUser(user);
        if (TorF<=0) {
            request.setAttribute("registerMsg","注册失败！");
            return Constants.REDIRECT + request.getContextPath()+"/register.jsp";
        }else {
            request.setAttribute("registerMsg","注册成功！");
            EmailUtils.sendEmail(user);
            return Constants.REDIRECT + request.getContextPath()+"/registerSuccess.jsp";

        }
    }

    public String logOut(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.removeAttribute("loginUser");

        Cookie cookie = new Cookie(Constants.AUTO_NAME, "");
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);

        session.setAttribute("msg","注销成功");
        return Constants.REDIRECT+request.getContextPath()+"/goods?method=index";

    }

}
